<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="出库单号">
              <a-input placeholder="请输入出库单号" v-model="queryParam.outboundNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="出库类型">
              <j-dict-select-tag
                placeholder="请选择出库类型"
                v-model="queryParam.outboundType"
                dictCode="wms_outbound_type"
              />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="状态">
              <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="wms_outbound_status" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <a-form-item label="订单号">
                <a-input placeholder="请输入订单号" v-model="queryParam.orderNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="领料单号">
                <a-input placeholder="请输入领料单号" v-model="queryParam.requisitionNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="出库日期">
                <j-date placeholder="请选择出库日期" v-model="queryParam.outboundDate" :showTime="true" />
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="upload" @click="handleImportRemaining" v-if="hasPermission('wms:outbound:add')"
        >导入余料出库单</a-button
      >
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('出库单')">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="outboundTypeSlot" slot-scope="text">
          <a-tag :color="getOutboundTypeColor(text)">
            {{ getOutboundTypeText(text) }}
          </a-tag>
        </template>

        <template slot="statusSlot" slot-scope="text">
          <a-tag :color="getStatusColor(text)">
            {{ getStatusText(text) }}
          </a-tag>
        </template>

        <!-- 订单编号列 - 支持悬停显示完整内容 -->
        <template slot="orderNoSlot" slot-scope="text">
          <a-tooltip :title="text" placement="topLeft">
            <div class="order-no-cell">{{ text }}</div>
          </a-tooltip>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">查看</a>
          <a-divider type="vertical" v-if="record.status === '1'" />
          <a @click="handleAudit(record)" v-if="record.status === '1'">审核</a>
          <a-divider type="vertical" v-if="record.status === '2' || record.status === '5'" />
          <a
            @click="handleOneClickOutbound(record)"
            v-if="record.status === '2' || record.status === '5'"
            style="color: #52c41a"
          >
            <a-icon type="export" />一键出库
          </a>
          <a-divider type="vertical" />
          <a @click="handlePrint(record)">打印</a>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <outbound-modal ref="modalForm" @ok="modalFormOk"></outbound-modal>
    <outbound-detail ref="detailModal"></outbound-detail>
    <outbound-audit ref="auditModal" @ok="modalFormOk"></outbound-audit>
    <outbound-print ref="printModal"></outbound-print>

    <!-- 导入余料出库单模态框 -->
    <a-modal
      title="导入余料出库单"
      :visible="importModalVisible"
      @ok="handleImportConfirm"
      @cancel="handleImportCancel"
      :confirmLoading="importLoading"
      width="1200px"
      :destroyOnClose="true"
    >
      <div v-if="!importData.length">
        <a-upload-dragger
          :fileList="fileList"
          :beforeUpload="beforeUpload"
          :remove="handleRemove"
          accept=".xlsx,.xls"
          :multiple="false"
        >
          <p class="ant-upload-drag-icon">
            <a-icon type="inbox" />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p class="ant-upload-hint">
            支持单个Excel文件上传，文件格式：.xlsx 或 .xls<br />
            请确保Excel文件包含以下列：出库单号、系列、物料名称、物料编码、物料颜色、物料长度、出库数量、订单编号
          </p>
        </a-upload-dragger>
        <div style="margin-top: 16px">
          <a-button type="primary" @click="handleParseFile" :loading="parseLoading" :disabled="!selectedFile">
            解析文件
          </a-button>
        </div>
      </div>

      <div v-else>
        <div style="margin-bottom: 16px">
          <a-alert
            message="文件解析成功"
            :description="`共解析到 ${importData.length} 条数据，请检查数据是否正确`"
            type="success"
            show-icon
          />
        </div>

        <a-table
          :columns="importColumns"
          :dataSource="importData"
          :pagination="false"
          size="small"
          :scroll="{ x: 1500, y: 300 }"
          :rowClassName="getImportRowClassName"
        >
          <!-- 订单编号列 - 支持悬停显示完整内容 -->
          <template slot="orderNoSlot" slot-scope="text">
            <a-tooltip :title="text" placement="topLeft">
              <div class="order-no-cell">{{ text }}</div>
            </a-tooltip>
          </template>
          <template slot="action" slot-scope="text, record, index">
            <a-button type="link" size="small" @click="removeImportRow(index)">删除</a-button>
          </template>
        </a-table>

        <div style="margin-top: 16px">
          <a-button @click="resetImport" style="margin-right: 8px">重新上传</a-button>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { OutboundModal, OutboundDetail, OutboundAudit, OutboundPrint } from '@/views/wms/outbound/modules'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { mixinDevice } from '@/utils/mixin'
import { getAction, postAction, putAction } from '@/api/manage'
import { saveRemainingMaterialOutbound } from '@/api/wms/outbound'

export default {
  name: 'OutboundList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    OutboundModal,
    OutboundDetail,
    OutboundAudit,
    OutboundPrint,
  },
  data() {
    return {
      description: '出库单管理',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 120,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '出库单号',
          align: 'center',
          dataIndex: 'outboundNo',
        },
        {
          title: '出库类型',
          align: 'center',
          dataIndex: 'outboundType',
          scopedSlots: { customRender: 'outboundTypeSlot' },
        },
        {
          title: '出库日期',
          align: 'center',
          dataIndex: 'outboundDate',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '关联订单号',
          align: 'center',
          dataIndex: 'orderNo',
          scopedSlots: { customRender: 'orderNoSlot' },
        },
        {
          title: '关联单号',
          align: 'center',
          dataIndex: 'requisitionNo',
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/outbound/list',
        delete: '/wms/outbound/delete',
        deleteBatch: '/wms/outbound/deleteBatch',
        exportXlsUrl: 'wms/outbound/exportXls',
        importExcelUrl: 'wms/outbound/importExcel',
        cancel: '/wms/outbound/cancel',
        execute: '/wms/outbound/execute',
        oneClickOutbound: '/wms/outbound/oneClickOutbound',
      },
      // 展开高级搜索条件
      toggleSearchStatus: false,
      // 导入参数
      importParams: {
        statusColumnIndex: 4,
        statusColumnName: '状态',
        importLoading: false,
      },
      importModalVisible: false,
      importLoading: false,
      parseLoading: false,
      fileList: [],
      selectedFile: null,
      importData: [],
      importColumns: [
        { title: '出库单号', dataIndex: 'outboundNo', width: 150 },
        { title: '系列', dataIndex: 'series', width: 150 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '物料编码', dataIndex: 'materialCode', width: 150 },
        { title: '物料颜色', dataIndex: 'materialColor', width: 150 },
        { title: '物料长度（m）', dataIndex: 'materialLength', width: 150 },
        { title: '出库数量', dataIndex: 'outboundQuantity', width: 150 },
        { title: '订单编号', dataIndex: 'orderNo', width: 150, scopedSlots: { customRender: 'orderNoSlot' } },
        { title: '仓库编号', dataIndex: 'warehouseCode', width: 150 },
        { title: '仓库名称', dataIndex: 'warehouseName', width: 150 },
        { title: '库位编号', dataIndex: 'locationCode', width: 150 },
        { title: '库位名称', dataIndex: 'locationName', width: 150 },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 80 },
      ],
      dictOptions: {},
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    // 提交审核
    handleSubmit(record) {
      // 更新状态为待审核
      let obj = {
        id: record.id,
        status: '1',
      }
      putAction('/wms/outbound/edit', obj).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    // 审核
    handleAudit(record) {
      this.$refs.auditModal.show(record)
      this.$refs.auditModal.title = '审核'
    },

    // 获取出库类型颜色 出库类型：1-销售出库，2-生产领料，3-调拨出库，4-其他出库
    getOutboundTypeColor(type) {
      const colorMap = {
        1: 'blue', // 销售出库
        2: 'green', // 生产领料
        3: 'orange', // 调拨出库
        4: 'purple', // 其他出库
      }
      return colorMap[type] || 'default'
    },

    // 获取出库类型文本
    getOutboundTypeText(type) {
      const textMap = {
        1: '销售出库',
        2: '生产领料',
        3: '调拨出库',
        4: '其他出库',
      }
      return textMap[type] || type
    },

    // 获取状态颜色
    getStatusColor(status) {
      const colorMap = {
        0: 'default', // 草稿
        1: 'orange', // 待审核
        2: 'blue', // 已审核
        3: 'green', // 已出库
        4: 'red', // 已取消
        5: 'yellow', // 部分出库
      }
      return colorMap[status] || 'default'
    },

    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        0: '草稿',
        1: '待审核',
        2: '已审核',
        3: '已出库',
        4: '已取消',
        5: '部分出库',
      }
      return textMap[status] || status
    },

    // 取消
    handleCancel(record) {
      this.$confirm({
        title: '确认取消',
        content: '确定取消该出库单吗?',
        onOk: () => {
          putAction(this.url.cancel, { id: record.id }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
        },
      })
    },

    // 执行出库
    handleExecute(record) {
      this.$confirm({
        title: '确认出库',
        content: '确定执行出库操作吗?',
        onOk: () => {
          putAction(this.url.execute, { id: record.id }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
        },
      })
    },

    // 查看详情
    handleDetail(record) {
      this.$refs.detailModal.show(record)
      this.$refs.detailModal.title = '详情'
    },

    // 打印
    handlePrint(record) {
      this.$refs.printModal.show(record)
      this.$refs.printModal.title = '打印出库单'
    },

    // 一键出库
    handleOneClickOutbound(record) {
      const statusText = record.status === '0' ? '待出库' : '部分出库'
      this.$confirm({
        title: '确认一键出库',
        content: `确定对该${statusText}出库单执行一键出库操作吗？系统将根据分配方案自动更新库存并完成出库。`,
        okText: '确认出库',
        cancelText: '取消',
        onOk: () => {
          this.executeOneClickOutbound(record)
        },
      })
    },

    // 执行一键出库
    executeOneClickOutbound(record) {
      const loading = this.$message.loading('正在执行一键出库...', 0)
      putAction(`${this.url.oneClickOutbound}?id=${record.id}`)
        .then((res) => {
          loading()
          if (res.success) {
            this.$message.success(res.message || '一键出库成功')
            this.loadData()
          } else {
            this.$message.error(res.message || '一键出库失败')
          }
        })
        .catch((err) => {
          loading()
          console.error('一键出库失败:', err)
          this.$message.error('一键出库失败，请稍后重试')
        })
    },

    // 切换高级查询
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },

    // 导入余料出库单相关方法
    handleImportRemaining() {
      this.importModalVisible = true
      this.resetImport()
    },

    // 重置导入状态
    resetImport() {
      this.fileList = []
      this.selectedFile = null
      this.importData = []
      this.parseLoading = false
    },

    // 文件上传前处理
    beforeUpload(file) {
      const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('只能上传Excel文件！')
        return false
      }

      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB！')
        return false
      }

      this.selectedFile = file
      this.fileList = [file]
      return false // 阻止自动上传
    },

    // 移除文件
    handleRemove() {
      this.selectedFile = null
      this.fileList = []
    },

    // 解析Excel文件
    handleParseFile() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择文件')
        return
      }

      this.parseLoading = true
      const formData = new FormData()
      formData.append('file', this.selectedFile)

      postAction('/wms/outbound/parseRemainingMaterialFile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
        .then((res) => {
          if (res.success) {
            this.importData = res.result || []
            if (this.importData.length === 0) {
              this.$message.warning('文件中没有有效数据')
            } else {
              this.$message.success(`成功解析${this.importData.length}条数据`)
            }
          } else {
            this.$message.error(res.message || '文件解析失败')
          }
        })
        .catch((error) => {
          console.error('解析文件失败:', error)
          this.$message.error('文件解析失败，请检查文件格式')
        })
        .finally(() => {
          this.parseLoading = false
        })
    },

    // 删除导入数据行
    removeImportRow(index) {
      this.importData.splice(index, 1)
    },

    // 确认导入
    handleImportConfirm() {
      if (!this.importData.length) {
        this.$message.warning('没有可导入的数据')
        return
      }

      // 检查是否有未绑定库位的物料
      const unboundMaterials = this.importData.filter((item) => !item.warehouseCode || !item.locationCode)

      if (unboundMaterials.length > 0) {
        const materialCodes = unboundMaterials.map((item) => item.materialCode).join(', ')
        this.$error({
          title: '无法导入',
          content: `以下物料编号暂无库存信息：${materialCodes}。`,
          okText: '知道了',
        })
        return
      }

      this.performImport()
    },

    // 执行导入操作
    performImport() {
      this.importLoading = true
      saveRemainingMaterialOutbound({
        dataList: this.importData,
      })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message || '导入成功！')
            this.handleImportCancel()
            this.loadData() // 刷新列表
          } else {
            this.$message.error(res.message || '导入失败')
          }
        })
        .catch((error) => {
          console.error('导入失败:', error)
          this.$message.error('导入时发生错误: ' + error.message)
        })
        .finally(() => {
          this.importLoading = false
        })
    },

    // 获取导入表格行样式类名
    getImportRowClassName(record) {
      // 如果没有仓库编号或库位编号，则标红显示
      if (!record.warehouseCode || !record.locationCode) {
        return 'import-row-error'
      }
      return ''
    },

    // 取消导入
    handleImportCancel() {
      this.importModalVisible = false
      this.importData = []
      this.resetImport()
    },

    // 获取订单编号的第一行
    getFirstOrderNo(text) {
      if (!text) return ''
      // 按换行符分割，取第一行
      const lines = text.toString().split(/[\r\n]+/)
      return lines[0] || ''
    },

    // 权限检查方法
    hasPermission(permission) {
      // 简单的权限检查，实际项目中应该根据用户权限进行判断
      return true
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/common.less';

/* 订单编号单元格样式 - 只显示首行，其余隐藏 */
.order-no-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100px;
  line-height: 1.5;
  cursor: pointer;
}
</style>